package com.css.zfzx.sjcj.modules.hddcGeophySvyLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.repository.HddcGeophysvylineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.repository.HddcGeophysvylineRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.repository.entity.HddcGeophysvylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.service.HddcGeophysvylineService;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.viewobjects.HddcGeophysvylineQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.viewobjects.HddcGeophysvylineVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-28
 */
@Service
public class HddcGeophysvylineServiceImpl implements HddcGeophysvylineService {

	@Autowired
    private HddcGeophysvylineRepository hddcGeophysvylineRepository;
    @Autowired
    private HddcGeophysvylineNativeRepository hddcGeophysvylineNativeRepository;

    @Override
    public JSONObject queryHddcGeophysvylines(HddcGeophysvylineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeophysvylineEntity> hddcGeophysvylinePage = this.hddcGeophysvylineNativeRepository.queryHddcGeophysvylines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeophysvylinePage);
        return jsonObject;
    }


    @Override
    public HddcGeophysvylineEntity getHddcGeophysvyline(String id) {
        HddcGeophysvylineEntity hddcGeophysvyline = this.hddcGeophysvylineRepository.findById(id).orElse(null);
         return hddcGeophysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvylineEntity saveHddcGeophysvyline(HddcGeophysvylineEntity hddcGeophysvyline) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeophysvyline.setUuid(uuid);
        hddcGeophysvyline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeophysvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeophysvyline.setIsValid("1");
        hddcGeophysvyline.setQualityinspectionStatus("0");
        hddcGeophysvyline.setExtends10("1");
        this.hddcGeophysvylineRepository.save(hddcGeophysvyline);
        return hddcGeophysvyline;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGeophysvylineEntity> saveHddcGeophysvylineList(List<HddcGeophysvylineEntity> list) {
        for (HddcGeophysvylineEntity hddcGeophysvyline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeophysvyline.setUuid(uuid);
            hddcGeophysvyline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeophysvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeophysvyline.setIsValid("1");
            hddcGeophysvyline.setQualityinspectionStatus("0");
            hddcGeophysvyline.setExtends10("1");
        }
        return hddcGeophysvylineNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvylineEntity updateHddcGeophysvyline(HddcGeophysvylineEntity hddcGeophysvyline) {
        HddcGeophysvylineEntity entity = hddcGeophysvylineRepository.findById(hddcGeophysvyline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeophysvyline);
        hddcGeophysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeophysvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeophysvylineRepository.save(hddcGeophysvyline);
        return hddcGeophysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeophysvylines(List<String> ids) {
        List<HddcGeophysvylineEntity> hddcGeophysvylineList = this.hddcGeophysvylineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvylineList) && hddcGeophysvylineList.size() > 0) {
            for(HddcGeophysvylineEntity hddcGeophysvyline : hddcGeophysvylineList) {
                hddcGeophysvyline.setIsValid("0");
                hddcGeophysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvyline.setUpdateTime(new Date());
                this.hddcGeophysvylineRepository.save(hddcGeophysvyline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeophysvylineQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeophysvylineEntity> yhDisasterEntities = hddcGeophysvylineNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeophysvylineVO> list=new ArrayList<>();
        for (HddcGeophysvylineEntity entity:yhDisasterEntities) {
            HddcGeophysvylineVO yhDisasterVO=new HddcGeophysvylineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地球物理测线-线", "地球物理测线-线", HddcGeophysvylineVO.class, "地球物理测线-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeophysvylineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeophysvylineVO.class, params);
            List<HddcGeophysvylineVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeophysvylineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeophysvylineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeophysvylineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeophysvylineEntity yhDisasterEntity = new HddcGeophysvylineEntity();
            HddcGeophysvylineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeophysvyline(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeophysvylineEntity> hddcGeophysvylineList = this.hddcGeophysvylineRepository.queryHddcGeophysvylinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvylineList) && hddcGeophysvylineList.size() > 0) {
            for(HddcGeophysvylineEntity hddcGeophysvyline : hddcGeophysvylineList) {
                hddcGeophysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeophysvyline.setIsValid("0");
                this.hddcGeophysvylineRepository.save(hddcGeophysvyline);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeophysvylineEntity> hddcGeophysvylineList = this.hddcGeophysvylineRepository.queryHddcGeophysvylinesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvylineList) && hddcGeophysvylineList.size() > 0) {
            for(HddcGeophysvylineEntity hddcGeophysvyline : hddcGeophysvylineList) {
                hddcGeophysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeophysvyline.setIsValid("0");
                this.hddcGeophysvylineRepository.save(hddcGeophysvyline);
            }
        }
    }

    @Override
    public void savehddcGeophysvylineServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {

        if(list!=null&&list.size()>0){
            List<HddcGeophysvylineEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcGeophysvylineEntity data = new HddcGeophysvylineEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setProjectid(obs.get(2).toString());
                data.setFieldid(obs.get(3).toString());
                data.setName(obs.get(4).toString());
                data.setSvylinesource(Integer.valueOf(obs.get(5).toString()));
                data.setCollectedlinesource(obs.get(6).toString());
                data.setPurpose(obs.get(7).toString());
                data.setSvymethod(Integer.valueOf(obs.get(8).toString()));
                data.setStartmilestonenum(Integer.valueOf(obs.get(9).toString()));
                data.setEndmilestonenum(Integer.valueOf(obs.get(10).toString()));
                data.setLength(Double.valueOf(obs.get(11).toString()));
                data.setResultname(obs.get(12).toString());
                data.setExpdataArwid(obs.get(13).toString());
                data.setResultmapArwid(obs.get(14).toString());
                data.setResultmapAiid(obs.get(15).toString());
                data.setFaultptprofileAiid(obs.get(16).toString());
                data.setFaultptprofileArwid(obs.get(17).toString());
                data.setShowcode(Integer.valueOf(obs.get(18).toString()));
                data.setCommentInfo(obs.get(19).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcGeophysvylineList(datas);
        }
    }


    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGeophysvylineEntity> hddcGeophysvylineList = this.hddcGeophysvylineRepository.queryHddcGeophysvylineByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvylineList) && hddcGeophysvylineList.size() > 0) {
            hddcGeophysvylineRepository.deleteAll(hddcGeophysvylineList);
        }
    }



    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("ProjectID")){
            str+="ProjectID,";
        }
        if(!set.contains("FieldID")){
            str+="FieldID,";
        }
        if(!set.contains("Name")){
            str+="Name,";
        }
        if(!set.contains("SvyLineSource")){
            str+="SvyLineSource,";
        }
        if(!set.contains("CollectedLineSource")){
            str+="CollectedLineSource,";
        }
        if(!set.contains("Purpose")){
            str+="Purpose,";
        }
        if(!set.contains("SvyMethod")){
            str+="SvyMethod,";
        }
        if(!set.contains("StartMilestoneNum")){
            str+="StartMilestoneNum,";
        }
        if(!set.contains("EndMilestoneNum")){
            str+="EndMilestoneNum,";
        }
        if(!set.contains("Length")){
            str+="Length,";
        }
        if(!set.contains("ResultName")){
            str+="ResultName,";
        }
        if(!set.contains("ExpData_ARWID")){
            str+="ExpData_ARWID,";
        }
        if(!set.contains("ResultMap_ARWID")){
            str+="ResultMap_ARWID,";
        }
        if(!set.contains("ResultMap_AIID")){
            str+="ResultMap_AIID,";
        }
        if(!set.contains("FaultPtProfile_AIID")){
            str+="FaultPtProfile_AIID,";
        }
        if(!set.contains("FaultPtProfile_ARWID")){
            str+="FaultPtProfile_ARWID,";
        }
        if(!set.contains("ShowCode")){
            str+="ShowCode,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;

    }

    @Override
    public List<HddcGeophysvylineEntity> findAll() {
        List<HddcGeophysvylineEntity> list=this.hddcGeophysvylineRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGeophysvylineRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

}
